<template>
  <a-card :bordered="false" :loading="loading">
    <DynamicForm
      :data-source="dataColumn"
      :model-data="{ ...detailData, roleId: detailData?.role?.id }"
      @submit-form="submitForm"
      @cancel="closeTab"
    ></DynamicForm>
  </a-card>
</template>

<script setup lang="tsx">
  import { message } from 'ant-design-vue';
  import DynamicForm from '@/components/dynamicForm/index.vue';
  import useRequestDetail from '@/hooks/useRequestDetail';
  import { sysUserApi, updateAdminInfo } from '@/api/system/user';
  import { getRoleListJson } from '@/api/system/role';
  import { useTabsViewStore } from '@/store/modules/tabsView';
  import { ComponentsTypeEnum } from '@/enums/componentsEnum';
  import { emailRegExp, encryptByMd5, mobileRegExp } from '@/utils/common';

  defineOptions({
    name: 'accountSetting',
  });
  const route = useRoute();
  const tabsViewStore = useTabsViewStore();
  const roleOption = ref<{ [x: string]: any }[]>([]);
  const dataColumn = ref([
    {
      field: 'username',
      component: ComponentsTypeEnum.Input,
      label: '登录账号',
      colProps: {
        span: 12,
      },
      componentProps: {
        disabled: true,
      },
      rules: [{ required: true }, { max: 30, message: '账号长度最大为30' }],
    },
    {
      field: 'avatar',
      component: ComponentsTypeEnum.Upload,
      label: '头像',
      colProps: {
        span: 12,
      },
      isUpload: true,
      componentProps: {
        maxCount: 1,
      },
      rules: [{ required: true, message: '请上传头像' }],
    },
    {
      field: 'nickname',
      component: ComponentsTypeEnum.Input,
      label: '呢称',
      colProps: {
        span: 12,
      },
      rules: [{ required: true }],
    },
    {
      field: 'mobile',
      component: ComponentsTypeEnum.Input,
      label: '手机号码',
      colProps: {
        span: 12,
      },
      rules: [{ required: true, message: '请输入正确的手机号码', pattern: mobileRegExp }],
    },
    {
      field: 'email',
      component: ComponentsTypeEnum.Input,
      label: '邮箱',
      colProps: {
        span: 12,
      },
      rules: [{ required: false, message: '请输入正确的邮箱', pattern: emailRegExp }],
    },
  ]);
  const { detailData, loading } = useRequestDetail({
    apiKey: sysUserApi.sysUserTokenInfo,
    isLoginRequired: true,
  });
  const getRoleOption = async () => {
    const data = await getRoleListJson();
    if (data) {
      roleOption.value = data;
    } else {
      roleOption.value = [];
    }
  };
  const submitForm = async (params) => {
    const userId = detailData.value?.id;
    params.password = params.password ? encryptByMd5(params.password) : '';
    const res = await updateAdminInfo({ ...params, id: userId });
    if (res) {
      message.success(res?.msg);
      closeTab();
    }
  };

  const closeTab = () => {
    tabsViewStore.closeCurrentTab(route);
  };
  onMounted(async () => await getRoleOption());
</script>

<style></style>
